<template>
  <div class="system-config-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">系统配置管理</h1>
        <p class="page-subtitle">
          管理系统各项配置参数，包括积分、订单、分销等模块配置
        </p>
      </div>
    </div>

    <div class="content-card">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="配置分组">
            <el-select
              v-model="searchForm.configGroup"
              placeholder="请选择配置分组"
              clearable
              style="width: 150px"
            >
              <el-option label="积分配置" value="integral" />
              <el-option label="订单配置" value="order" />
              <el-option label="分销配置" value="distribution" />
            </el-select>
          </el-form-item>
          <el-form-item label="配置状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="配置描述">
            <el-input
              v-model="searchForm.configDesc"
              placeholder="请输入配置描述关键词"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 配置列表 -->
      <div class="config-list">
        <div
          v-for="config in filteredConfigList"
          :key="config.id"
          class="config-item"
        >
          <div class="config-header">
            <div class="config-info">
              <div class="config-title">
                <span class="config-name">{{ config.configDesc }}</span>
                <el-tag
                  :type="getGroupTagType(config.configGroup)"
                  size="small"
                  class="group-tag"
                >
                  {{ getGroupLabel(config.configGroup) }}
                </el-tag>
                <el-tag
                  :type="config.status === 1 ? 'success' : 'info'"
                  size="small"
                  class="status-tag"
                >
                  {{ config.status === 1 ? "启用" : "禁用" }}
                </el-tag>
              </div>
              <div class="config-key">配置键: {{ config.configKey }}</div>
            </div>
            <div class="config-actions">
              <el-button
                type="primary"
                size="small"
                @click="editConfig(config)"
              >
                编辑
              </el-button>
              <el-switch
                v-model="config.status"
                :active-value="1"
                :inactive-value="0"
                @change="toggleConfigStatus(config)"
                :loading="config.statusLoading"
              />
            </div>
          </div>

          <div class="config-content">
            <div class="config-preview">
              <div class="preview-title">当前配置值:</div>
              <div class="preview-content">
                <pre>{{ formatConfigValue(config.configValueObj) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredConfigList.length === 0" class="empty-state">
        <el-empty description="暂无配置数据" />
      </div>
    </div>

    <!-- 编辑配置对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="`编辑配置 - ${editingConfig?.configDesc}`"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-form-item label="配置分组" prop="configGroup">
          <el-select
            v-model="editForm.configGroup"
            placeholder="请选择配置分组"
            style="width: 100%"
            disabled
          >
            <el-option label="积分配置" value="integral" />
            <el-option label="订单配置" value="order" />
            <el-option label="分销配置" value="distribution" />
          </el-select>
        </el-form-item>

        <el-form-item label="配置键" prop="configKey">
          <el-input
            v-model="editForm.configKey"
            placeholder="配置键"
            disabled
          />
        </el-form-item>

        <el-form-item label="配置描述" prop="configDesc">
          <el-input
            v-model="editForm.configDesc"
            placeholder="配置描述"
            disabled
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- <el-form-item label="配置状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- 动态配置值编辑 -->
        <el-form-item label="配置值" prop="configValueObj">
          <div class="config-value-editor">
            <!-- 签到积分奖励配置 -->
            <template v-if="editForm.configKey === 'sign_reward'">
              <div class="sign-reward-config">
                <div class="config-section">
                  <h4>连续签到积分奖励配置</h4>
                  <div class="reward-list">
                    <div
                      v-for="(_point, index) in editForm.configValueObj.points"
                      :key="index"
                      class="reward-item"
                    >
                      <span class="day-label">第{{ index + 1 }}天:</span>
                      <el-input-number
                        v-model="editForm.configValueObj.points[index]"
                        :min="0"
                        :precision="0"
                        size="small"
                        style="width: 120px"
                      />
                      <span class="unit">积分</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>

            <!-- 订单返积分比例配置 -->
            <template v-else-if="editForm.configKey === 'order_reward_ratio'">
              <div class="ratio-config">
                <div class="config-section">
                  <h4>订单金额返积分比例</h4>
                  <div class="ratio-item">
                    <span class="label">返积分比例:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.ratio"
                      :min="0"
                      :max="1"
                      :precision="3"
                      :step="0.001"
                      style="width: 150px"
                    />
                    <span class="unit">(0-1之间)</span>
                  </div>
                  <div class="ratio-item">
                    <span class="label">最高积分:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.max_points"
                      :min="0"
                      :precision="0"
                      style="width: 150px"
                    />
                    <span class="unit">积分</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 积分抵扣规则配置 -->
            <template v-else-if="editForm.configKey === 'deduction_rule'">
              <div class="deduction-config">
                <div class="config-section">
                  <h4>积分抵扣规则</h4>
                  <div class="deduction-item">
                    <span class="label">抵扣比例:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.ratio"
                      :min="0"
                      :max="1"
                      :precision="3"
                      :step="0.001"
                      style="width: 150px"
                    />
                    <span class="unit">(0-1之间)</span>
                  </div>
                  <div class="deduction-item">
                    <span class="label">积分兑换比例:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.points_per_yuan"
                      :min="1"
                      :precision="0"
                      style="width: 150px"
                    />
                    <span class="unit">积分=1元</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 注册奖励配置 -->
            <template v-else-if="editForm.configKey === 'register_reward'">
              <div class="reward-config">
                <div class="config-section">
                  <h4>新用户注册奖励</h4>
                  <div class="reward-item">
                    <span class="label">赠送积分:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.points"
                      :min="0"
                      :precision="0"
                      style="width: 150px"
                    />
                    <span class="unit">积分</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 绑定手机奖励配置 -->
            <template v-else-if="editForm.configKey === 'bind_mobile_reward'">
              <div class="reward-config">
                <div class="config-section">
                  <h4>绑定手机奖励</h4>
                  <div class="reward-item">
                    <span class="label">赠送积分:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.points"
                      :min="0"
                      :precision="0"
                      style="width: 150px"
                    />
                    <span class="unit">积分</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 订单超时配置 -->
            <template v-else-if="editForm.configKey === 'cancel_timeout'">
              <div class="timeout-config">
                <div class="config-section">
                  <h4>订单自动取消时间</h4>
                  <div class="timeout-item">
                    <span class="label">超时时间:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.minutes"
                      :min="1"
                      :precision="0"
                      style="width: 150px"
                    />
                    <span class="unit">分钟</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 自动完成订单配置 -->
            <template v-else-if="editForm.configKey === 'auto_complete'">
              <div class="complete-config">
                <div class="config-section">
                  <h4>签收后自动完成订单</h4>
                  <div class="complete-item">
                    <span class="label">自动完成时间:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.days"
                      :min="1"
                      :precision="0"
                      style="width: 150px"
                    />
                    <span class="unit">天</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 运费配置 -->
            <template v-else-if="editForm.configKey === 'shipping_fee'">
              <div class="shipping-config">
                <div class="config-section">
                  <h4>运费配置</h4>
                  <div class="shipping-item">
                    <span class="label">默认运费:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.default_fee"
                      :min="0"
                      :precision="2"
                      style="width: 150px"
                    />
                    <span class="unit">元</span>
                  </div>
                  <div class="shipping-item">
                    <span class="label">免运费门槛:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.free_threshold"
                      :min="0"
                      :precision="2"
                      style="width: 150px"
                    />
                    <span class="unit">元</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 分销佣金配置 -->
            <template v-else-if="editForm.configKey === 'commission_ratio'">
              <div class="commission-config">
                <div class="config-section">
                  <h4>三级分销佣金比例</h4>
                  <div class="commission-item">
                    <span class="label">一级分销:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.level1"
                      :min="0"
                      :max="1"
                      :precision="3"
                      :step="0.001"
                      style="width: 150px"
                    />
                    <span class="unit">(0-1之间)</span>
                  </div>
                  <div class="commission-item">
                    <span class="label">二级分销:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.level2"
                      :min="0"
                      :max="1"
                      :precision="3"
                      :step="0.001"
                      style="width: 150px"
                    />
                    <span class="unit">(0-1之间)</span>
                  </div>
                  <div class="commission-item">
                    <span class="label">三级分销:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.level3"
                      :min="0"
                      :max="1"
                      :precision="3"
                      :step="0.001"
                      style="width: 150px"
                    />
                    <span class="unit">(0-1之间)</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 提现配置 -->
            <template v-else-if="editForm.configKey === 'withdraw_setting'">
              <div class="withdraw-config">
                <div class="config-section">
                  <h4>提现配置</h4>
                  <div class="withdraw-item">
                    <span class="label">最低提现金额:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.min_amount"
                      :min="0"
                      :precision="2"
                      style="width: 150px"
                    />
                    <span class="unit">元</span>
                  </div>
                  <div class="withdraw-item">
                    <span class="label">手续费比例:</span>
                    <el-input-number
                      v-model="editForm.configValueObj.fee_ratio"
                      :min="0"
                      :max="1"
                      :precision="3"
                      :step="0.001"
                      style="width: 150px"
                    />
                    <span class="unit">(0-1之间)</span>
                  </div>
                </div>
              </div>
            </template>

            <!-- 默认配置值编辑器 -->
            <template v-else>
              <div class="default-config">
                <div class="config-section">
                  <h4>配置值 (JSON格式)</h4>
                  <el-input
                    v-model="configValueJson"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入JSON格式的配置值"
                    @input="updateConfigValueFromJson"
                  />
                </div>
              </div>
            </template>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveConfig" :loading="saving">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getWithAuth, postWithAuth } from "@/utils/request";

// 响应式数据
const loading = ref(false);
const saving = ref(false);
const editDialogVisible = ref(false);
const editFormRef = ref();
const configValueJson = ref("");

// 配置列表
const configList = ref<any[]>([]);

// 搜索表单
const searchForm = reactive({
  configGroup: "",
  status: undefined as number | undefined,
  configDesc: "",
});

// 编辑表单
const editForm = reactive({
  id: "",
  configGroup: "",
  configKey: "",
  configDesc: "",
  status: 1,
  configValueObj: {} as any,
});

// 当前编辑的配置
const editingConfig = ref<any>(null);

// 表单验证规则
const editRules = {
  configDesc: [
    { required: true, message: "请输入配置描述", trigger: "blur" },
    { max: 200, message: "配置描述不能超过200个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择配置状态", trigger: "change" }],
};

// 计算属性：过滤后的配置列表
const filteredConfigList = computed(() => {
  let filtered = configList.value;

  if (searchForm.configGroup) {
    filtered = filtered.filter(
      (config) => config.configGroup === searchForm.configGroup
    );
  }

  if (searchForm.status !== undefined) {
    filtered = filtered.filter((config) => config.status === searchForm.status);
  }

  if (searchForm.configDesc) {
    filtered = filtered.filter((config) =>
      config.configDesc.includes(searchForm.configDesc)
    );
  }

  return filtered;
});

// 获取配置列表
const fetchConfigList = async () => {
  loading.value = true;
  try {
    const result = await getWithAuth("/internal/system/config/getAllConfig");
    if (result.code === 0) {
      configList.value = result.data || [];
    } else {
      ElMessage.error(result.message || "获取配置列表失败");
    }
  } catch (error) {
    console.error("获取配置列表失败:", error);
    ElMessage.error("获取配置列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 重置搜索
const resetSearch = () => {
  searchForm.configGroup = "";
  searchForm.status = undefined;
  searchForm.configDesc = "";
};

// 编辑配置
const editConfig = (config: any) => {
  editingConfig.value = config;
  editForm.id = config.id;
  editForm.configGroup = config.configGroup;
  editForm.configKey = config.configKey;
  editForm.configDesc = config.configDesc;
  editForm.status = config.status;
  editForm.configValueObj = JSON.parse(JSON.stringify(config.configValueObj));

  // 更新JSON显示
  configValueJson.value = JSON.stringify(config.configValueObj, null, 2);

  editDialogVisible.value = true;
};

// 保存配置
const saveConfig = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    saving.value = true;

    const params = {
      id: editForm.id,
      configGroup: editForm.configGroup,
      configKey: editForm.configKey,
      configDesc: editForm.configDesc,
      status: editForm.status,
      configValueObj: editForm.configValueObj,
    };

    const result = await postWithAuth(
      "/internal/system/config/updateConfig",
      params
    );

    if (result.code === 0) {
      ElMessage.success("配置更新成功");
      editDialogVisible.value = false;
      await fetchConfigList(); // 重新获取列表
    } else {
      ElMessage.error(result.message || "更新失败");
    }
  } catch (error) {
    console.error("保存配置失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

// 切换配置状态
const toggleConfigStatus = async (config: any) => {
  try {
    config.statusLoading = true;

    const result = await postWithAuth(
      `/internal/system/config/updateConfigStatus/${config.id}`,
      {}
    );

    if (result.code === 0) {
      ElMessage.success(`配置已${config.status === 1 ? "启用" : "禁用"}`);
    } else {
      // 如果更新失败，恢复原状态
      config.status = config.status === 1 ? 0 : 1;
      ElMessage.error(result.message || "状态更新失败");
    }
  } catch (error) {
    // 如果更新失败，恢复原状态
    config.status = config.status === 1 ? 0 : 1;
    console.error("切换配置状态失败:", error);
    ElMessage.error("状态更新失败");
  } finally {
    config.statusLoading = false;
  }
};

// 更新配置值从JSON
const updateConfigValueFromJson = () => {
  try {
    const parsed = JSON.parse(configValueJson.value);
    editForm.configValueObj = parsed;
  } catch (error) {
    // JSON解析失败时不更新
  }
};

// 格式化配置值显示
const formatConfigValue = (configValueObj: any) => {
  return JSON.stringify(configValueObj, null, 2);
};

// 获取分组标签类型
const getGroupTagType = (group: string) => {
  const types: { [key: string]: string } = {
    integral: "success",
    order: "warning",
    distribution: "info",
  };
  return types[group] || "default";
};

// 获取分组标签文本
const getGroupLabel = (group: string) => {
  const labels: { [key: string]: string } = {
    integral: "积分配置",
    order: "订单配置",
    distribution: "分销配置",
  };
  return labels[group] || group;
};

// 页面加载时获取配置列表
onMounted(() => {
  fetchConfigList();
});
</script>

<style scoped>
.system-config-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #718096;
  margin: 0;
  font-size: 16px;
}

.content-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.search-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.config-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.config-item {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  background: #f7fafc;
  transition: all 0.3s ease;
}

.config-item:hover {
  border-color: #4299e1;
  box-shadow: 0 2px 8px rgba(66, 153, 225, 0.1);
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.config-info {
  flex: 1;
}

.config-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.config-name {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.group-tag {
  margin-left: 8px;
}

.status-tag {
  margin-left: 8px;
}

.config-key {
  font-size: 14px;
  color: #718096;
  font-family: monospace;
}

.config-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.config-content {
  border-top: 1px solid #e2e8f0;
  padding-top: 16px;
}

.config-preview {
  background: white;
  border-radius: 6px;
  padding: 12px;
  border: 1px solid #e2e8f0;
}

.preview-title {
  font-size: 14px;
  font-weight: 500;
  color: #4a5568;
  margin-bottom: 8px;
}

.preview-content pre {
  margin: 0;
  font-size: 12px;
  color: #2d3748;
  background: #f7fafc;
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

/* 配置值编辑器样式 */
.config-value-editor {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  background: #f7fafc;
}

.config-section h4 {
  margin: 0 0 16px 0;
  font-size: 14px;
  font-weight: 600;
  color: #2d3748;
}

.reward-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.reward-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.day-label {
  min-width: 60px;
  font-size: 14px;
  color: #4a5568;
}

.ratio-item,
.deduction-item,
.reward-item,
.timeout-item,
.complete-item,
.shipping-item,
.commission-item,
.withdraw-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.label {
  min-width: 100px;
  font-size: 14px;
  color: #4a5568;
}

.unit {
  font-size: 12px;
  color: #718096;
  margin-left: 4px;
}

.default-config {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-config-management {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .page-title {
    font-size: 20px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .content-card {
    padding: 16px;
  }

  .config-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .config-actions {
    justify-content: space-between;
  }

  .config-item {
    padding: 16px;
  }

  .config-title {
    flex-wrap: wrap;
  }

  .config-name {
    font-size: 14px;
  }

  .reward-item,
  .ratio-item,
  .deduction-item,
  .reward-item,
  .timeout-item,
  .complete-item,
  .shipping-item,
  .commission-item,
  .withdraw-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .label,
  .day-label {
    min-width: auto;
  }
}

@media (max-width: 480px) {
  .system-config-management {
    padding: 12px;
  }

  .content-card {
    padding: 12px;
  }

  .config-item {
    padding: 12px;
  }

  .config-name {
    font-size: 13px;
  }

  .config-key {
    font-size: 12px;
  }
}
</style>
